﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace GetComics.Silverlight
{
    public class ResizableCanvas : SuperCanvas
    {
        private Rectangle _transRect;
        private bool _mouseCaptured;
        private List<Rectangle> _verticalPoints;
        private List<Rectangle> _horizontalPoints;


        public ResizableCanvas()
            : base()
        {
            this.MouseLeftButtonDown += new MouseButtonEventHandler(ResizableCanvas_MouseLeftButtonDown);

        }


        public FrameworkElement ElementToResize
        {
            get;
            set;
        }

        void ResizableCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ElementToResize != null)
                CreateTransRect(ElementToResize);
        }

        /// <summary>
        /// Добавляет к элементу прямоугольник с точками для ресайза
        /// </summary>
        /// <param name="element"></param>
        private void CreateTransRect(FrameworkElement element)
        {
            if (_transRect == null)
            {
                _transRect = new Rectangle();
                _transRect.SetValue(Canvas.NameProperty, "transformRect");
                _transRect.Height = element.Height;
                _transRect.Width = element.Width;
                _transRect.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
                _transRect.Stroke = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
                this.Children.Add(_transRect);
                //Canvas.SetTop(transRect, Canvas.GetTop(element));
                //Canvas.SetLeft(transRect, Canvas.GetLeft(element));
                Canvas.SetZIndex(_transRect, Canvas.GetZIndex(element) - 1);

                CreateTransRectPoints(_transRect);
            }
        }
        /// <summary>
        /// Добавляет к прямоугольнику точки для ресайза
        /// </summary>
        /// <param name="transRect"></param>
        private void CreateTransRectPoints(Rectangle transRect)
        {
            _verticalPoints = new List<Rectangle>(2);
            _horizontalPoints = new List<Rectangle>(2);

            Rectangle rectPoint;
            rectPoint =  CreateTransPointRect();
            rectPoint.MouseLeftButtonDown += new MouseButtonEventHandler(rectPoint_MouseLeftButtonDown);
            rectPoint.MouseLeftButtonUp += new MouseButtonEventHandler(rectPoint_MouseLeftButtonUp);
            rectPoint.MouseMove += new MouseEventHandler(rectPoint_MouseMoveTop);
            rectPoint.Cursor = Cursors.SizeNS;
            rectPoint.Tag = new Dragger(false, true);
            this.AddDragable(rectPoint);
            _verticalPoints.Add(rectPoint);
            // координаты по левому углу прямоугольника
            Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3);
            Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3 + transRect.Width / 2);

            rectPoint = CreateTransPointRect();
            rectPoint.MouseLeftButtonDown += new MouseButtonEventHandler(rectPoint_MouseLeftButtonDown);
            rectPoint.MouseLeftButtonUp += new MouseButtonEventHandler(rectPoint_MouseLeftButtonUp);
            rectPoint.MouseMove += new MouseEventHandler(rectPoint_MouseMoveDown);
            rectPoint.Cursor = Cursors.SizeNS;
            rectPoint.Tag = new Dragger(false, true);
            this.AddDragable(rectPoint);
            _verticalPoints.Add(rectPoint);
            // координаты по левому углу прямоугольника
            Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3 + transRect.Height);
            Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3 + transRect.Width / 2);

            rectPoint = CreateTransPointRect();
            rectPoint.MouseLeftButtonDown += new MouseButtonEventHandler(rectPoint_MouseLeftButtonDown);
            rectPoint.MouseLeftButtonUp += new MouseButtonEventHandler(rectPoint_MouseLeftButtonUp);
            rectPoint.MouseMove += new MouseEventHandler(rectPoint_MouseMoveRight);
            rectPoint.Cursor = Cursors.SizeWE;
            rectPoint.Tag = new Dragger(true, false);
            this.AddDragable(rectPoint);
            _horizontalPoints.Add(rectPoint);
            // координаты по левому углу прямоугольника
            Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3 + transRect.Height / 2);
            Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3 + transRect.Width);

            rectPoint = CreateTransPointRect();
            rectPoint.MouseLeftButtonDown += new MouseButtonEventHandler(rectPoint_MouseLeftButtonDown);
            rectPoint.MouseLeftButtonUp += new MouseButtonEventHandler(rectPoint_MouseLeftButtonUp);
            rectPoint.MouseMove += new MouseEventHandler(rectPoint_MouseMoveLeft);
            rectPoint.Cursor = Cursors.SizeWE;
            rectPoint.Tag = new Dragger(true, false);
            this.AddDragable(rectPoint);
            _horizontalPoints.Add(rectPoint);
            // координаты по левому углу прямоугольника
            Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3 + transRect.Height / 2);
            Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3);


            // Закомментим пока угловые точки не разобрался как сделать курсор ресайз по диагонали

            //rectPoint = CreateTransPointRect();
            //canv.Children.Add(rectPoint);
            //// координаты по левому углу прямоугольника
            //Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3);
            //Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3);

            //rectPoint = CreateTransPointRect();
            //canv.Children.Add(rectPoint);
            //// координаты по левому углу прямоугольника
            //Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3);
            //Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3 + transRect.Width);

            //rectPoint = CreateTransPointRect();
            //canv.Children.Add(rectPoint);
            //// координаты по левому углу прямоугольника
            //Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3 + transRect.Height);
            //Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3 + transRect.Width);

            //rectPoint = CreateTransPointRect();
            //canv.Children.Add(rectPoint);
            //// координаты по левому углу прямоугольника
            //Canvas.SetTop(rectPoint, Canvas.GetTop(transRect) - 3 + transRect.Height);
            //Canvas.SetLeft(rectPoint, Canvas.GetLeft(transRect) - 3);
        }

        void rectPoint_MouseMoveLeft(object sender, MouseEventArgs e)
        {
            if (_mouseCaptured)
            {
                double originLeft = Canvas.GetLeft(_transRect);
                double setLeft = e.GetPosition(this).X;
                double delta = originLeft - setLeft;
                _transRect.Width += delta;
                ElementToResize.Width += delta;
                Canvas.SetLeft(_transRect, setLeft);
                Canvas.SetLeft(ElementToResize, setLeft);
                foreach (Rectangle el in _verticalPoints)
                {
                    Canvas.SetLeft(el, setLeft + _transRect.Width / 2);
                }               
            }
        }

        void rectPoint_MouseMoveRight(object sender, MouseEventArgs e)
        {
            if (_mouseCaptured)
            {
                double originRight = Canvas.GetLeft(_transRect) + _transRect.Width;
                double setRight = e.GetPosition(this).X;
                double delta = setRight - originRight;
                _transRect.Width += delta;
                ElementToResize.Width += delta;
                foreach (Rectangle el in _verticalPoints)
                {
                    Canvas.SetLeft(el, originRight - _transRect.Width / 2);
                }                 
            }
        }

        void rectPoint_MouseMoveDown(object sender, MouseEventArgs e)
        {
            if (_mouseCaptured)
            {
                double originDown = Canvas.GetTop(_transRect) + _transRect.Height;
                double setDown = e.GetPosition(this).Y;
                double delta = setDown - originDown;
                _transRect.Height += delta;
                ElementToResize.Height += delta;
                foreach (Rectangle el in _horizontalPoints)
                {
                    Canvas.SetTop(el, originDown - _transRect.Height / 2);
                }                
            }
        }

        void rectPoint_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Rectangle r = (Rectangle)sender;
            r.ReleaseMouseCapture();
            _mouseCaptured = false;             
        }

        void rectPoint_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Rectangle r = (Rectangle)sender;
            r.CaptureMouse();
            _mouseCaptured = true;            
        }

        void rectPoint_MouseMoveTop(object sender, MouseEventArgs e)
        {
            if (_mouseCaptured)
            {
                double originTop = Canvas.GetTop(_transRect);
                double setTop = e.GetPosition(this).Y;
                double deltaTop = originTop - setTop;
                _transRect.Height += deltaTop;
                ElementToResize.Height += deltaTop;
                Canvas.SetTop(_transRect, setTop);
                Canvas.SetTop(ElementToResize, setTop);
                foreach (Rectangle el in _horizontalPoints)
                {
                    Canvas.SetTop(el, originTop + _transRect.Height / 2);
                }                
            }
        }
        /// <summary>
        /// Создает маленький прямоугольник, за который можно будет тянуть и ресайзить
        /// </summary>
        /// <returns></returns>
        private Rectangle CreateTransPointRect()
        {
            Rectangle rectPoint;
            rectPoint = new Rectangle();
            rectPoint.Height = 6;
            rectPoint.Width = 6;
            rectPoint.Fill = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
            rectPoint.Stroke = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
            rectPoint.RenderTransform = new TransformGroup { Children = new TransformCollection { new TranslateTransform() } };
            return rectPoint;
        }
    }
}
